package com.xpgk.mvc.collection.measurement;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.codec.binary.Base64;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.DateUtil;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;
import com.xpgk.annotation.Service;
import com.xpgk.constant.ConstantRender;
import com.xpgk.dto.RenderBean;
import com.xpgk.mvc.base.BaseService;
import com.xpgk.mvc.bentryRegister.BentryRegisterService;
import com.xpgk.mvc.bentryRegister.Customer;
import com.xpgk.mvc.bentryRegister.CustomerAgreement;
import com.xpgk.mvc.bentryRegister.CustomerDetail;
import com.xpgk.mvc.bentryRegister.CustomerProduct;
import com.xpgk.mvc.bentryRegister.CustomerProductSurplus;
import com.xpgk.mvc.bloseWeight.DelWeiTargetSum;
import com.xpgk.mvc.codeSet.Code;
import com.xpgk.mvc.measurement.Temporary;
import com.xpgk.mvc.organization.Organization;
import com.xpgk.mvc.productSales.ProductSales;
import com.xpgk.mvc.productSales.ProductSalesOrder;
import com.xpgk.mvc.productSet.Product;
import com.xpgk.mvc.statistic.dailyTotalStatistic.DailyNursingTotal;
import com.xpgk.mvc.statistic.monthTotalStatistic.MonthTotal;
import com.xpgk.mvc.statistic.yearTotalStatistic.YearTotal;
import com.xpgk.tools.ToolDateTime;
import com.xpgk.tools.ToolRandoms;
import com.xpgk.tools.security.ToolPbkdf2;

@Service(name = CollectionTemporaryServices.serviceName)
public class CollectionTemporaryServices extends BaseService {

	public static final String serviceName = "collectionTemporaryServices";

	@SuppressWarnings("unused")
	private static final Log log = Log.getLog(CollectionTemporaryServices.class);

	/**
	 * 查询编号
	 */
	public String getNumber(String organids) {
		// 获取当月
		SimpleDateFormat df = new SimpleDateFormat("yyMM");
		String date = df.format(new Date());
	
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("column", CollectionTemporary.column_organIds);
		String sql = getSqlByBeetl(CollectionTemporary.sqlId_column, param);
		List<CollectionTemporary> temList = CollectionTemporary.dao.find(sql, organids);
		
		ArrayList<Integer> numList = new ArrayList<Integer>();
		if (temList != null && temList.size() > 0) {
			for (CollectionTemporary tem : temList) {
				String number = tem.getStr(CollectionTemporary.column_number);
				int n = Integer.parseInt(number.substring(number.length() - 3, number.length()));
				numList.add(n);
			}
			int a = Collections.max(numList);

			return date + String.format("%03d", a + 1);
		} else {
			return date + "001";
		}
	}

	/**
	 * 保存测算数据
	 */
	public Map<String, Object> saveRecord(CollectionTemporary temp, String organids) {

		String msg = ConstantRender.render_success_code;
		Map<String, Object> mm = new HashMap<>();
		if (temp != null) {
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("column", Customer.column_phone);
			String sql = getSqlByBeetl(Customer.sqlId_column, param);
			Customer cus = Customer.dao.findFirst(sql, temp.getStr(CollectionTemporary.column_phone));
			if (cus != null) {
				// 已成交顾客
				log.debug("该顾客已为成交顾客，无需再次测算！！");
				// msg="测算信息保存失败！！";
				// throw new RuntimeException("该顾客已为成交顾客，不需要再次测算!");
				msg = "该顾客已为成交顾客，无需再次测算！！";
			} else {
				// 未成交顾客
				float stdWeight = getStdWeight(temp.getStr("sex"), temp.getInt("height"), temp.getInt("age"));
				if (stdWeight != 0) {
					mm.put("stdWeight", stdWeight);
					DecimalFormat decimalFormat = new DecimalFormat(".0");
					float delWeight = temp.getFloat(CollectionTemporary.column_weight) - stdWeight;
					mm.put("delWeight", decimalFormat.format(delWeight));
					int treatment = getTreatment(Float.parseFloat(decimalFormat.format(delWeight)));
					mm.put("goal", treatment);
					
					if (treatment == 1) {
						Record r = Db.findFirst("SELECT outPrice FROM sb_product_price WHERE priceIds=? and productName = '一疗程带售后' and status ='1'",Organization.dao.findById(organids).getStr(Organization.column_priceIds));
						if(r!=null){
						mm.put("cost", r.getFloat("outPrice"));
						}else{
							msg = "请设置疗程(一疗程)价格！";
						}
					} else {
						Record r = Db.findFirst("SELECT outPrice FROM sb_product_price WHERE priceIds=? and productName = '标准疗程' and status ='1'",Organization.dao.findById(organids).getStr(Organization.column_priceIds));
						if(r!=null){
						mm.put("cost", treatment * r.getFloat("outPrice"));
						}else{
							msg = "请设置疗程(标准疗程)价格！";
						}
					}
					CollectionTemporary oldTemp = CollectionTemporary.dao.getTodayRecord(temp.getStr(CollectionTemporary.column_phone));
					if (oldTemp != null) {
						temp.set("treatment", treatment).set("ids", oldTemp.getStr("ids"))
								.set(CollectionTemporary.column_number, oldTemp.getStr(CollectionTemporary.column_number)).set("dataStatus","1");
						if (!temp.update()) {
							log.debug("测算信息更新失败！！");
							throw new RuntimeException("测算信息更新失败!");
						}
					} else {
//						temp.set("organIds", organids).set("treatment", treatment).set("gxsj", new Date());
						temp.set("organIds", organids).set("treatment", treatment).set(Temporary.column_updateDate, new Date());
						if (!temp.save()) {
							log.debug("测算信息保存失败！！");
							throw new RuntimeException("测算信息保存失败!");
						}
						
					}
					//保存日护理综合查询（新顾客咨询人数）
					DailyNursingTotal  dnt = DailyNursingTotal.dao.getDnt(organids,temp.getDate(Temporary.column_gxsj));
					if(dnt != null)
					{
						dnt.set(DailyNursingTotal.column_zxrs, dnt.getInt(DailyNursingTotal.column_zxrs)+1);
						if (!dnt.update()) {
							log.debug("更新日护理综合查询（新顾客咨询人数失败）！！");
							throw new RuntimeException("更新日护理综合查询（新顾客咨询人数失败）!");
						}
					}else
					{
						DailyNursingTotal dnt1= new DailyNursingTotal();
						dnt1.set(DailyNursingTotal.column_organids, organids)
							.set(DailyNursingTotal.column_date, ToolDateTime.format(temp.getDate(Temporary.column_gxsj), ToolDateTime.pattern_ymd))
							.set(DailyNursingTotal.column_zxrs, 1);
						if (!dnt1.save()) {
							log.debug("保存日护理综合查询（新顾客咨询人数失败）！！");
							throw new RuntimeException("保存日护理综合查询（新顾客咨询人数失败）!");
						}
					}
					//保存月综合查询（新顾客咨询人数）
					MonthTotal mt = MonthTotal.dao.getMonthTotal(organids,temp.getDate(Temporary.column_gxsj));
					if(mt != null)
					{
						mt.set(MonthTotal.column_zxrs, mt.getInt(MonthTotal.column_zxrs)+1);
						if (!mt.update()) {
							log.debug("更新月综合查询（新顾客咨询人数失败）！！");
							throw new RuntimeException("更新月综合查询（新顾客咨询人数失败）!");
						}
					}else
					{
						mt= new MonthTotal();
						mt.set(MonthTotal.column_organids, organids)
							.set(MonthTotal.column_date, ToolDateTime.format(temp.getDate(Temporary.column_gxsj), ToolDateTime.pattern_ym))
							.set(MonthTotal.column_zxrs, 1);
						if (!mt.save()) {
							log.debug("保存月综合查询（新顾客咨询人数失败）！！");
							throw new RuntimeException("保存月综合查询（新顾客咨询人数失败）!");
						}
					}
					//保存年综合查询（新顾客咨询人数）
					YearTotal yt = YearTotal.dao.getYearTotal(organids,temp.getDate(Temporary.column_gxsj));
					if(yt != null)
					{
						yt.set(YearTotal.column_zxrs, yt.getInt(YearTotal.column_zxrs)+1);
						if (!yt.update()) {
							log.debug("更新年综合查询（新顾客咨询人数失败）！！");
							throw new RuntimeException("更新年综合查询（新顾客咨询人数失败）!");
						}
					}else
					{
						yt= new YearTotal();
						yt.set(YearTotal.column_organids, organids)
							.set(YearTotal.column_date, ToolDateTime.format(temp.getDate(Temporary.column_gxsj), ToolDateTime.pattern_y))
							.set(YearTotal.column_zxrs, 1);
						if (!yt.save()) {
							log.debug("保存年综合查询（新顾客咨询人数失败）！！");
							throw new RuntimeException("保存年综合查询（新顾客咨询人数失败）!");
						}
					}
					mm.put("treatment", treatment);
					
				} else {
					log.debug("输入的年龄，身高，体重有误，无法与标准体重进行测算，请重新输入！");
					// msg="输入的年龄，身高，体重有误，无法与标准体重进行测算，请重新输入！";
					// throw new
					// RuntimeException("输入的年龄，身高，体重有误，无法与标准体重进行测算，请重新输入！");
					msg = "输入的年龄，身高，体重有误，无法与标准体重进行测算，请重新输入！";
				}
			}

		}
		mm.put("msg", msg);
		return mm;
	}

	/**
	 * 获取介绍人门店
	 * 
	 * @param jsrPhone
	 */
	public RenderBean getJsrStore(String jsrPhone) {
		RenderBean result = new RenderBean();
		String orgSql = getSqlMy(CollectionTemporary.sqlId_selOrgByCusPhone);
		Organization org = Organization.dao.findFirst(orgSql, jsrPhone,jsrPhone);
		if (org != null) {
			result.setCode(ConstantRender.render_success_code);
			result.setMode(org);
			result.setMsg("2");
		} else {
			String orgSql2 = getSqlMy(Customer.sqlId_selOrgByCusPhone1);
			Organization org2 = Organization.dao.findFirst(orgSql2, jsrPhone,jsrPhone);
			if (org2 != null) {
				result.setCode(ConstantRender.render_success_code);
				result.setMode(org2);
				result.setMsg("1");
			} else {
				result.setCode(ConstantRender.render_error_code);
				result.setMsg("用户不存在！");
			}

		}
		return result;
}

	/**
	 * 保存顾客详细信息
	 * 
	 * @param temp
	 * @param cus
	 * @param cusDet
	 * @param cusAgr
	 * @param cusdet2 
	 */
	public RenderBean saveTempAndCus(String organname, CollectionTemporary temp, CustomerAgreement cusAgr, String delWeight,
			String targetWeight, String cudid, String chargePersion, String userIds,String customerIds, CustomerDetail cusDet) {
		String msg = "";
		String cusIds = "";
		
		
		
		
		RenderBean result = new RenderBean();
		String temSql = getSqlMy(CollectionTemporary.sqlId_selTemByNum);
		// Temporary oldTemp =
		// Temporary.dao.findFirst(temSql,temp.getStr(Temporary.column_number));
		CollectionTemporary oldTemp = CollectionTemporary.dao.getTemporary(temp.getStr(CollectionTemporary.column_phone));
		if (oldTemp != null) {
			int tre = cusAgr.getInt(CustomerAgreement.column_treatment);
			oldTemp.set(CollectionTemporary.column_standWeight, cusAgr.getFloat(CustomerAgreement.column_std_weight));
			oldTemp.set(CollectionTemporary.column_treatment, tre + "");
			oldTemp.set(CollectionTemporary.column_targetWeight, targetWeight);
			oldTemp.set(CollectionTemporary.column_delWeight, delWeight);
			oldTemp.set(CollectionTemporary.column_weightDay, cusAgr.getInt(CustomerAgreement.column_target) + "");
			oldTemp.set(CollectionTemporary.column_cost, cusAgr.getDouble(CustomerAgreement.column_cost));
			oldTemp.set(CollectionTemporary.column_organIds, cudid);
			oldTemp.set(CollectionTemporary.column_loseReason, temp.getStr(CollectionTemporary.column_loseReason));
			oldTemp.set(CollectionTemporary.column_gxsj, temp.getDate(CollectionTemporary.column_gxsj));
			oldTemp.set(CollectionTemporary.column_jdfs, temp.getStr(CollectionTemporary.column_jdfs));
			oldTemp.set(CollectionTemporary.column_jsrIds, temp.getStr(CollectionTemporary.column_jsrIds));
			oldTemp.set(CollectionTemporary.column_jsrName, temp.getStr(CollectionTemporary.column_jsrName));
			oldTemp.set(CollectionTemporary.column_jsrPhone, temp.getStr(CollectionTemporary.column_jsrPhone));
			oldTemp.set(CollectionTemporary.column_jsrorg, temp.getStr(CollectionTemporary.column_jsrorg));
			oldTemp.set(CollectionTemporary.column_jsrtype, temp.getStr(CollectionTemporary.column_jsrtype));
			oldTemp.set(CollectionTemporary.column_gkfl, temp.getStr(CollectionTemporary.column_gkfl));
			//oldTemp.set(CollectionTemporary.column_gkfy, temp.getStr(CollectionTemporary.column_gkfy));
			oldTemp.set(CollectionTemporary.column_fzr, chargePersion);
			oldTemp.set(CollectionTemporary.column_jdr, temp.getStr(CollectionTemporary.column_jdr));
			oldTemp.set(CollectionTemporary.column_updateDate, new Date());
			oldTemp.set(CollectionTemporary.column_updateId, userIds);
			oldTemp.set(CollectionTemporary.column_dataStatus, 2);
			// .set(Temporary.column_treatment,
			// oldTemp.getStr(Temporary.column_treatment))
			// .set("ids", oldTemp.getStr("ids"));
			if (!oldTemp.update()) {
				log.debug("测算信息更新失败！！");
				throw new RuntimeException("测算信息更新失败!");
			}
		} else {
			int tre = cusAgr.getInt(CustomerAgreement.column_treatment);
			temp.set(CollectionTemporary.column_treatment, tre + "");
			temp.set(CollectionTemporary.column_standWeight, cusAgr.getFloat(CustomerAgreement.column_std_weight));
			temp.set(CollectionTemporary.column_targetWeight, targetWeight);
			temp.set(CollectionTemporary.column_delWeight, delWeight);
			temp.set(CollectionTemporary.column_weightDay, cusAgr.getInt(CustomerAgreement.column_target) + "");
			temp.set(CollectionTemporary.column_cost, cusAgr.getDouble(CustomerAgreement.column_cost));
			temp.set(CollectionTemporary.column_loseReason, temp.getStr(CollectionTemporary.column_loseReason));
			temp.set(CollectionTemporary.column_jdfs, temp.getStr(CollectionTemporary.column_jdfs));
			temp.set(CollectionTemporary.column_jsrIds, temp.getStr(CollectionTemporary.column_jsrIds));
			temp.set(CollectionTemporary.column_jsrName, temp.getStr(CollectionTemporary.column_jsrName));
			temp.set(CollectionTemporary.column_jsrorg, temp.getStr(CollectionTemporary.column_jsrorg));
			temp.set(CollectionTemporary.column_jsrPhone, temp.getStr(CollectionTemporary.column_jsrPhone));
			temp.set(CollectionTemporary.column_jsrtype, temp.getStr(CollectionTemporary.column_jsrtype));
			temp.set(CollectionTemporary.column_gkfl, temp.getStr(CollectionTemporary.column_gkfl));
			//temp.set(CollectionTemporary.column_gkfy, temp.getStr(CollectionTemporary.column_gkfy));
			temp.set(CollectionTemporary.column_createDate, new Date());
			temp.set(CollectionTemporary.column_createId, userIds);
			temp.set(CollectionTemporary.column_fzr, chargePersion);
			temp.set(CollectionTemporary.column_dataStatus, 2);
			if (!temp.save()) {
				log.debug("测算信息保存失败！！");
				throw new RuntimeException("测算信息保存失败!");
			}
			
		}
		// 如果测算信息的顾客分类ids等于code表成交顾客ids
		if (temp.getStr(CollectionTemporary.column_gkfl).equals(Code.cjCus_ids)) {
			Customer cus = new Customer();
		
			// 保存顾客登记信息
			
			cus.set(Customer.column_userName, temp.getStr(CollectionTemporary.column_phone));
			try {
				byte[] salt = ToolPbkdf2.generateSalt();// 密码盐
				byte[] encryptedPassword = ToolPbkdf2.getEncryptedPassword("123456", salt);
				cus.set(Customer.column_salt, Base64.encodeBase64String(salt));
				cus.set(Customer.column_password, Base64.encodeBase64String(encryptedPassword));
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			// 通过当前机构id获取机构编码
			// String cuoBh=BentryRegisterService.getOrgBh(cudid);
			// 获取当前机构顾客的编号最大（也就是最新进店的顾客会员编号）
			// 通过机构编号模糊查询
			// String par="%"+cuoBh+"%";
			String chybh = "000001";
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("column", Customer.column_organIds);
			String sql = getSqlByBeetl(Customer.sqlId_column, param);
			List<Customer> clist = Customer.dao.find(sql, cudid);
			ArrayList<Integer> numList = new ArrayList<Integer>();
			if (clist != null && clist.size() > 0) {
				for (Customer cuss : clist) {
					String hybh = cuss.getStr(Customer.column_hybh);
					int n = Integer.parseInt(hybh);
					numList.add(n);
				}
				int a = Collections.max(numList);
				chybh = String.format("%06d", a + 1);
			}
			cus.set(Customer.column_hybh, chybh).set(Customer.column_organIds, cudid)
					.set(Customer.column_name, temp.getStr(CollectionTemporary.column_name))
					.set(Customer.column_age, temp.getInt(CollectionTemporary.column_age))
					.set(Customer.column_sex, temp.getStr(CollectionTemporary.column_sex))
					.set(Customer.column_phone, temp.getStr(CollectionTemporary.column_phone))
					.set(Customer.column_registtime, temp.getDate(CollectionTemporary.column_gxsj))
					.set(Customer.column_createDate, new Date())
					.set(Customer.column_createId, userIds)
					.set(Customer.column_state, "1")
					.set(Customer.column_dataStatus, 2);
			if (!cus.save( customerIds)) {
				log.debug("顾客信息保存失败！！");
				throw new RuntimeException("顾客信息保存失败!");
			}
			cusIds = cus.getStr(Customer.column_ids);
			if(cusDet==null) {
				cusDet = new CustomerDetail();
			}
			String cusDetids = ToolRandoms.getUuid(true);
			cusDet.set(CustomerDetail.column_ids, cusDetids).set(CustomerDetail.column_organName, organname)
					.set(CustomerDetail.column_phone, cus.getStr(Customer.column_phone))
					.set(CustomerDetail.column_name, cus.getStr(Customer.column_name))
					.set(CustomerDetail.column_hybh, cus.getStr(Customer.column_hybh))
					.set(CustomerDetail.column_standardWeight, cusAgr.get(CustomerAgreement.column_std_weight))
					.set(CustomerDetail.column_sex,  cus.getStr(Customer.column_sex))
					.set(CustomerDetail.column_age,  cus.getInt(Customer.column_age))
					.set(CustomerDetail.column_username, cus.getStr(Customer.column_userName))
					.set(CustomerDetail.column_organIds, cus.getStr(Customer.column_organIds))
					.set(CustomerDetail.column_customerIds, cus.getStr(Customer.column_ids))
					.set(CustomerDetail.column_height, temp.getInt(CollectionTemporary.column_height))
					.set(CustomerDetail.column_firstWeight, temp.getFloat(CollectionTemporary.column_weight))
					.set(CustomerDetail.column_firstDate, temp.getDate(CollectionTemporary.column_gxsj))
					.set(CustomerDetail.column_createDate, new Date())
					.set(CustomerDetail.column_minWeight,temp.getFloat(CollectionTemporary.column_weight))
					.set(CustomerDetail.column_minDate, new Date())
					.set(CustomerDetail.column_nowWeight, temp.getFloat(CollectionTemporary.column_weight))
					.set(CustomerDetail.column_toStoreDate,temp.getDate(CollectionTemporary.column_gxsj))
					.set(CustomerDetail.column_delWeight, delWeight)
					.set(CustomerDetail.column_targetWeight, targetWeight)
					.set(CustomerDetail.column_type, temp.getStr(CollectionTemporary.column_jdfs))
					.set(CustomerDetail.column_jsrIds, temp.getStr(CollectionTemporary.column_jsrIds))
					.set(CustomerDetail.column_jsrName, temp.getStr(CollectionTemporary.column_jsrName))
					.set(CustomerDetail.column_jsrorg, temp.getStr(CollectionTemporary.column_jsrorg))
					.set(CustomerDetail.column_jsrPhone, temp.getStr(CollectionTemporary.column_jsrPhone))
					.set(CustomerDetail.column_jsrtype, temp.getStr(CollectionTemporary.column_jsrtype))
					.set(CustomerDetail.column_createDate, new Date())
					.set(CustomerDetail.column_createId, userIds)
					.set(CustomerDetail.column_sjtreatment,cusAgr.getInt(CustomerAgreement.column_treatment)+"")
					.set(CustomerDetail.column_dataStatus, 2)
					.set(CustomerDetail.column_customerType, 0)
					.set(CustomerDetail.column_chargePersion, chargePersion);
			if(cusAgr.getStr(CustomerAgreement.column_codeIds).equals("0")){
				cusDet.set(CustomerDetail.column_customerType, 1);
			}
			

			// 根据疗程数求出结束的日期
			Date date = temp.getDate(CollectionTemporary.column_gxsj);
			
			Calendar cal = Calendar.getInstance();
			cal.setTime(date);
			cal.add(cal.MONTH, Integer.parseInt(cusAgr.get("target").toString()));
			SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			String lastMonth = dft.format(cal.getTime());

			// 保存总目标汇总表
			DelWeiTargetSum delWeiT = new DelWeiTargetSum();
			delWeiT.set(DelWeiTargetSum.column_ids, delWeiT).set(DelWeiTargetSum.column_targetName, "总目标")
					.set(DelWeiTargetSum.column_delWei, delWeight).set(DelWeiTargetSum.column_targetWei, targetWeight)
					.set(DelWeiTargetSum.column_customerIds, cus.get("ids").toString())
					.set(DelWeiTargetSum.column_startWei, temp.get("weight").toString())
					.set(DelWeiTargetSum.column_createId, userIds).set(DelWeiTargetSum.column_createDate, new Date())
					.set(DelWeiTargetSum.column_startTime, temp.getDate(CollectionTemporary.column_gxsj))
					.set(DelWeiTargetSum.column_dataStatus, 2)
					.set(DelWeiTargetSum.column_endTime, lastMonth);
					

			if (!delWeiT.save()) {
				log.debug("顾客总目标信息保存失败！");
				throw new RuntimeException("顾客总目标信息保存失败");
			}

			// 通过当前机构id获取机构编码
			String cuoBh = BentryRegisterService.getOrgBh(cudid);

			// 获取编号
			String bh = BentryRegisterService.getBH(cuoBh, cusAgr.getInt(CustomerAgreement.column_treatment),chybh,temp.getDate(CollectionTemporary.column_gxsj));

			// float
			// d=temp.getFloat(Temporary.column_weight)-Float.parseFloat(delWeight);
//			int treatment=cusAgr.getInt(CustomerAgreement.column_treatment);
			cusAgr.set(CustomerAgreement.column_customerID, cus.getStr(Customer.column_ids))
					.set(CustomerAgreement.column_organIds, cudid).set(CustomerAgreement.column_bh, bh)
					.set(CustomerAgreement.column_before_weight, temp.getFloat(CollectionTemporary.column_weight))
					.set(CustomerAgreement.column_after_weight, targetWeight).set(CustomerAgreement.column_isPay, "0")
					.set(CustomerAgreement.column_createId, userIds).set(CustomerAgreement.column_createDate, new Date())
					.set(CustomerAgreement.column_dataStatus, 2)
					.set(CustomerAgreement.column_time,  temp.getDate(CollectionTemporary.column_gxsj)).set(CustomerAgreement.column_state, "1");

			if (!cusAgr.save()) {
				log.debug("顾客协议保存失败！！");
				throw new RuntimeException("顾客协议保存失败!");
			}
			cusDet.set(CustomerDetail.column_agreementIds, cusAgr.getStr(CustomerAgreement.column_ids))
			.set(CustomerDetail.column_agreementBH,bh)
			.set(CustomerDetail.column_treatmentName,cusAgr.getStr(CustomerAgreement.column_codeIds));
			
			if (!cusDet.save()) {
				log.debug("顾客详细信息保存失败！！");
				throw new RuntimeException("顾客详细信息保存失败!");
			}
			//保存日综合查询表（新顾客成交人数，新顾客转介绍成交人数，新顾客宣传成交人数，新顾客自然进店成交人数，新顾客成交率，
			// 新顾客单疗程数，新顾客疗程数，新顾客应减斤数）
			DailyNursingTotal  dnt = DailyNursingTotal.dao.getDnt(cudid,temp.getDate(Temporary.column_gxsj));
			if(dnt != null)
			{
				dnt.set(DailyNursingTotal.column_cjrs, dnt.getInt(DailyNursingTotal.column_cjrs)+1);
				if(temp.getStr(Temporary.column_jdfs).equals(Code.zjs_ids))//如果是转介绍
				{
					dnt.set(DailyNursingTotal.column_zjscjrs, dnt.getInt(DailyNursingTotal.column_zjscjrs)+1);
				}else if(temp.getStr(Temporary.column_jdfs).equals(Code.xc_ids))//如果是宣传
				{
					dnt.set(DailyNursingTotal.column_xccjrs, dnt.getInt(DailyNursingTotal.column_xccjrs)+1);
				}else//自然进店
				{
					dnt.set(DailyNursingTotal.column_zrjdcjrs, dnt.getInt(DailyNursingTotal.column_zrjdcjrs)+1);
				}
				
				if(cusAgr.getStr(CustomerAgreement.column_codeIds).equals(Code.dlc_ids))
				{
					dnt.set(DailyNursingTotal.column_xgkDlcs, dnt.getInt(DailyNursingTotal.column_xgkDlcs)+cusAgr.getInt(CustomerAgreement.column_treatment));
				}else
				{
					dnt.set(DailyNursingTotal.column_xgkLcs, dnt.getInt(DailyNursingTotal.column_xgkLcs)+cusAgr.getInt(CustomerAgreement.column_treatment));
				}
				double  cjl = ((double)dnt.getInt(DailyNursingTotal.column_cjrs))/((double)dnt.getInt(DailyNursingTotal.column_zxrs))*100;
				dnt.set(DailyNursingTotal.column_xgkCjl, new DecimalFormat("#.00").format(cjl))
					.set(DailyNursingTotal.column_xgkYjjs, dnt.getDouble(DailyNursingTotal.column_xgkYjjs)+Double.parseDouble(delWeight));
				if (!dnt.update()) {
					log.debug("更新日综合查询失败！！");
					throw new RuntimeException("更新日综合查询失败!");
				}	
			}	
			
			//保存月综合查询表（新顾客成交人数，新顾客转介绍成交人数，新顾客宣传成交人数，新顾客自然进店成交人数，新顾客成交率，
			// 新顾客单疗程数，新顾客疗程数，新顾客应减斤数，当年当月新顾客应减斤数）
			MonthTotal mt = MonthTotal.dao.getMonthTotal(cudid,temp.getDate(Temporary.column_gxsj));
			if(mt != null)
			{
				mt.set(MonthTotal.column_cjrs, mt.getInt(MonthTotal.column_cjrs)+1);
				if(temp.getStr(Temporary.column_jdfs).equals(Code.zjs_ids))//如果是转介绍
				{
					mt.set(MonthTotal.column_zjscjrs, mt.getInt(MonthTotal.column_zjscjrs)+1);
				}else if(temp.getStr(Temporary.column_jdfs).equals(Code.xc_ids))//如果是宣传
				{
					mt.set(MonthTotal.column_xccjrs, mt.getInt(MonthTotal.column_xccjrs)+1);
				}else//自然进店
				{
					mt.set(MonthTotal.column_zrjdcjrs, mt.getInt(MonthTotal.column_zrjdcjrs)+1);
				}
				
				if(cusAgr.getStr(CustomerAgreement.column_codeIds).equals(Code.dlc_ids))
				{
					mt.set(MonthTotal.column_xgkDlcs, mt.getInt(MonthTotal.column_xgkDlcs)+cusAgr.getInt(CustomerAgreement.column_treatment));
				}else
				{
					mt.set(MonthTotal.column_xgkLcs, mt.getInt(MonthTotal.column_xgkLcs)+cusAgr.getInt(CustomerAgreement.column_treatment));
				}
				double  cjl = ((double)mt.getInt(MonthTotal.column_cjrs))/((double)mt.getInt(MonthTotal.column_zxrs))*100;
				mt.set(MonthTotal.column_xgkCjl, new DecimalFormat("#.00").format(cjl))
					.set(MonthTotal.column_xgkYjjs, mt.getDouble(MonthTotal.column_xgkYjjs)+Double.parseDouble(delWeight));
				if (!mt.update()) {
					log.debug("更新月综合查询失败！！");
					throw new RuntimeException("更新月综合查询失败!");
				}	
			}	
			//保存年综合查询表（新顾客成交人数，新顾客转介绍成交人数，新顾客宣传成交人数，新顾客自然进店成交人数，新顾客成交率，
			// 新顾客单疗程数，新顾客疗程数，新顾客应减斤数）
			YearTotal yt = YearTotal.dao.getYearTotal(cudid,temp.getDate(Temporary.column_gxsj));
			if(yt != null)
			{	
				Calendar calendar=Calendar.getInstance();
				int month=calendar.get(Calendar.MONTH)+1;
				int year = calendar.get(Calendar.YEAR);
				yt.set(YearTotal.column_cjrs, yt.getInt(YearTotal.column_cjrs)+1);
				if(temp.getStr(Temporary.column_jdfs).equals(Code.zjs_ids))//如果是转介绍
				{
					yt.set(YearTotal.column_zjscjrs, yt.getInt(YearTotal.column_zjscjrs)+1);
				}else if(temp.getStr(Temporary.column_jdfs).equals(Code.xc_ids))//如果是宣传
				{
					yt.set(YearTotal.column_xccjrs, yt.getInt(YearTotal.column_xccjrs)+1);
				}else//自然进店
				{
					yt.set(YearTotal.column_zrjdcjrs, yt.getInt(YearTotal.column_zrjdcjrs)+1);
				}
				
				if(cusAgr.getStr(CustomerAgreement.column_codeIds).equals(Code.dlc_ids))
				{
					yt.set(YearTotal.column_xgkDlcs, yt.getInt(YearTotal.column_xgkDlcs)+cusAgr.getInt(CustomerAgreement.column_treatment));
				}else
				{	
					yt.set(YearTotal.column_xgkLcs, yt.getInt(YearTotal.column_xgkLcs)+cusAgr.getInt(CustomerAgreement.column_treatment));
					
				}
				int ssyear= Integer.parseInt(dft.format(temp.getDate(Temporary.column_gxsj)).substring(0, 4));
				if(ssyear != year)
				{
					month = 12;
				}
				int yjlcs = 0;
				if(yt.getInt(YearTotal.column_cjrs) != 0)
				{
					yjlcs = (yt.getInt(YearTotal.column_xgkLcs)/yt.getInt(YearTotal.column_cjrs))/month;
				}
				yt.set(YearTotal.column_yjLcs, yjlcs);
				int yjcjrs = yt.getInt(YearTotal.column_cjrs)/month;
				yt.set(YearTotal.column_yjCjrs, yjcjrs);
				double  cjl = ((double)yt.getInt(YearTotal.column_cjrs))/((double)yt.getInt(YearTotal.column_zxrs))*100;
				yt.set(YearTotal.column_xgkCjl, new DecimalFormat("#.00").format(cjl))
				.set(YearTotal.column_xgkYjjs, yt.getDouble(YearTotal.column_xgkYjjs)+Double.parseDouble(delWeight));
				if (!yt.update()) {
					log.debug("更新年综合查询失败！！");
					throw new RuntimeException("更新年综合查询失败!");
				}	
			}	
			
			msg = ConstantRender.render_success_code;
		} else {
			msg = "1";
		}
		result.getMap().put("msg", msg);
		result.getMap().put("cusIds", cusIds);
		return result;
	}

	/**
	 * 用手机号搜索顾客信息
	 */
	public Map<String, Object> phoneSearch(String name, String phone, String orgid) {
		Map<String, Object> mm = new HashMap<>();
		Record r = null;
		Map<String, Object> queryParam = new HashMap<String, Object>();
		queryParam.put("phone", phone);
		queryParam.put("orgid", orgid);
		queryParam.put("name", name);

		String sql1 = "select * from sb_customer_temporary where organIds = ? and  (phone = ? or name = ?)and dataStatus=1  ";
		CollectionTemporary temporary = CollectionTemporary.dao.findFirst(sql1, orgid, phone, name);
		if (temporary != null) {
			String gkfl = temporary.getStr(CollectionTemporary.column_gkfl);
			if (gkfl.equals("607f10b77f4d4b908104e990f366a334")) {
				mm.put("msg", "该顾客已为成交顾客");
			} else {
				String visitsql = "SELECT IFNULL(count(*),0)  AS count FROM sb_customer_scallvisit WHERE  customerids = ? and visitType = 1";
				Record f = Db.findFirst(visitsql, temporary.getStr(CollectionTemporary.column_ids));
				mm.put("callvisitcount", f.get("count").toString());
				visitsql = "SELECT IFNULL(count(*),0)  AS count FROM sb_customer_scallvisit WHERE  customerids = ? and visitType = 2";
				f = Db.findFirst(visitsql, temporary.getStr(CollectionTemporary.column_ids));
				mm.put("toshopvisitcount", f.get("count").toString());

				CollectionTemporary r1 = temporary;
				mm.put("temporaryCustomerIds", r1.get("ids"));
				mm.put("name", r1.get("name"));
				mm.put("sex", r1.get("sex"));
				mm.put("phone", r1.get("phone"));
				mm.put("age", r1.get("age"));
				mm.put("weight", r1.get("weight"));
				mm.put("height", r1.get("height"));

				mm.put("delWeight", r1.get("delWeight"));
				mm.put("treatment", r1.get("treatment"));
				mm.put("targetWeight", r1.get("targetWeight"));
				mm.put("weightDay", r1.get("weightDay"));
				mm.put("cost", r1.get("cost"));
				mm.put("standWeight", r1.get("standWeight"));

				mm.put("jdfs", r1.get("jdfs"));
				mm.put("loseReason", r1.get("loseReason"));

				mm.put("jdr", r1.get("jdr"));
				mm.put("gkfy", r1.get("gkfy"));
				mm.put("gkfl", r1.get("gkfl"));
				
				String sql = getSqlMy("sb.temporary.querypeople");
				List<Record> result = Db.find(sql,  r1.get("ids"), 2, orgid);
				if(result!=null&&result.size()>0){
					mm.put("resultddfw", result);
				}
				
				result = Db.find(sql,  r1.get("ids"), 1, orgid);
				if(result!=null&&result.size()>0){
					mm.put("resultdhhw", result);
				}
				
				mm.put("msg", "200");
			}
		} else {
			mm.put("msg", "该顾客无本店测算信息");
		}
		return mm;
	}

	// /**
	// * 获取测算结果
	// */
	// public static String calculate(Float stdWeight, Float weight){
	//// float stdWeight = getStdWeight(sex, height, age);
	// String result;
	// if(stdWeight!=0)
	// {
	// float differ_weight = weight - stdWeight;
	// BigDecimal b = new BigDecimal(differ_weight);
	// float differ_weight1 = b.setScale(2,
	// BigDecimal.ROUND_HALF_UP).floatValue();
	// if(differ_weight<0)
	// {
	// result="0";
	// }else
	// {
	// result = "您的标准体重为" + stdWeight + "斤，实际测重为"
	// + weight + "斤，相差" + differ_weight1 + "斤，建议您选择" + getTreatment(weight,
	// stdWeight) + "疗程。";
	// }
	// }else
	// {
	// result="输入的年龄，身高，体重有误，无法与标准体重进行测算，请重新输入！";
	// }
	// return result;
	// }
	/**
	 * 测算获得标准体重
	 * 
	 * @param sex
	 * @param height
	 * @param age
	 * @return 斤
	 */
	public static float getStdWeight(String sex, int height, int age) {
		return CollectionStdWeightModel.me.getStdWeight(sex, height, age) * 2;
	}
	
	
	

	/**
	 * 测算获得疗程数
	 * 
	 * @param weight
	 * @param stdWeight
	 * @return
	 */
	public static int getTreatment(float differ_weight) {
		// float differ_weight = weight - stdWeight;
		if(differ_weight<0){
			return 0;
		}else{
			int lcs = (int)Math.ceil(differ_weight/10);
			return lcs;
		}
		
//		if (0 < differ_weight && differ_weight <= 10) {
//			return 1;
//		} else if (10 < differ_weight && differ_weight <= 20) {
//			return 2;
//		} else if (20 < differ_weight && differ_weight <= 30) {
//			return 3;
//		} else if (30 < differ_weight && differ_weight <= 40) {
//			return 4;
//		} else if (40 < differ_weight && differ_weight <= 50) {
//			return 5;
//		} else if (differ_weight <= 0) {
//			return 0;
//		} else {
//			return 6;
//		}
	}

	/**
	 * 根据编号查询数据
	 * 
	 * @param number编号
	 * @param obj（上一条下一条标识）
	 * @return
	 */
	public CollectionTemporary selOther(String number, String obj, String organids) {
		int n = Integer.parseInt(number.substring(number.length() - 3, number.length()));
		// String num="1705140100";
		// 获取当月
		SimpleDateFormat df = new SimpleDateFormat("yyMM");
		String date = df.format(new Date());
		// 获取当前代理商门店编号
		String dlmdBH = BentryRegisterService.getOrgBh(organids);
		String num = date + dlmdBH;
		if (obj != null) {
			if (obj.equals("1")) {
				log.debug("获取上一条数据");
				num += String.format("%03d", n - 1);
			}
			if (obj.equals("2")) {
				log.debug("获取下一条数据");
				num += String.format("%03d", n + 1);
			}
		} else {
			num = number;
		}

		String sql = getSqlMy(CollectionTemporary.sqlId_selTemByNum);
		CollectionTemporary tem = CollectionTemporary.dao.findFirst(sql, num);
		CollectionTemporary tem1 = CollectionTemporary.dao.findFirst(sql, number);
		if (tem != null || tem1 != null) {
			return tem;
		} else {
			// Temporary tem1=Temporary.dao.findFirst(sql,number);
			return null;
		}

	}

	/*
	 * 今日测算查询
	 */
	public List<Record> todaymeasure(String organids, String todaydate) {
		String sql = getSqlMy("sb.temporary.todaymeasure");
		List<Record> result = Db.find(sql, organids, todaydate);
		return result;
	}

	public List<CollectionTemporary> getCusInfo(String orgid) {
		String sql1 = "select * from sb_customer_temporary where organIds = ? and dataStatus=1 and gkfl != '607f10b77f4d4b908104e990f366a334'";
		List<CollectionTemporary> cbis = CollectionTemporary.dao.find(sql1, orgid);
		return cbis;
	}

	public List<CollectionTemporary> getCusAndUserInfo() {
		String sql1 = " (select ids, `name`,phone,organIds,sex  from  sb_customer_temporary )UNION(select ids,`name`,mobile,organizationids,organizationids from sys_user)";
		List<CollectionTemporary> cbis = CollectionTemporary.dao.find(sql1);
		return cbis;
	}
	
	

	public  Map<String, Object>  imageUpload(UploadFile file,String organIds,String userIds) {
		Map<String, Object> json = new HashMap<>();
		
		json.put("message","保存成功");
		String organName ="";
		String sqlorgan = "SELECT so.`name` FROM sys_organization so WHERE so.ids = ?";
		if(Db.findFirst(sqlorgan,organIds)!=null){
			organName = Db.findFirst(sqlorgan,organIds).getStr("name");
		}
		String path = file.getUploadPath()+"/"+ file.getFileName();
		//String path = file.getSaveDirectory() + file.getFileName();
		// 处理导入数据
		List<Map<Integer,String>> list = new ArrayList<Map<Integer,String>>();
		
		HSSFWorkbook hwb;
		try {
			hwb = new HSSFWorkbook(new FileInputStream(new File(path)));
			HSSFSheet sheet = hwb.getSheetAt(0); // 获取到第一个sheet中数据
		
			int num = sheet.getLastRowNum();
			System.out.println(num);
			for(int i = 1;i<sheet.getLastRowNum()+1; i++) {// 第二行开始取值，第一行为标题行
			HSSFRow row = sheet.getRow(i);// 获取到第i列的行数据(表格行)
			
			Map<Integer, String> map = new HashMap<Integer, String>();
			for(int j=0;j<row.getLastCellNum(); j++) {
			HSSFCell cell = row.getCell(j);// 获取到第j行的数据(单元格)
			if(cell != null){
				//1、判断是否是数值格式  
				if(cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC){  
				    short format = cell.getCellStyle().getDataFormat();  
				    SimpleDateFormat sdf = null;  
				    if(format == 14 || format == 31 || format == 57 || format == 58|| format == 176){  
				        //日期  
				        sdf = new SimpleDateFormat("yyyy-MM-dd"); 
				        double value = cell.getNumericCellValue();  
					    Date date = DateUtil.getJavaDate(value);  
					    map.put(j, sdf.format(date));
				    }else if (format == 20 || format == 32) {  
				        //时间  
				        sdf = new SimpleDateFormat("HH:mm");  
				        double value = cell.getNumericCellValue();  
					    Date date = DateUtil.getJavaDate(value);  
					    map.put(j, sdf.format(date));
				    }else{
				    	cell.setCellType(HSSFCell.CELL_TYPE_STRING);
						map.put(j, cell.getStringCellValue());
				    }
				  
				   
				}else{
					cell.setCellType(HSSFCell.CELL_TYPE_STRING);
					map.put(j, cell.getStringCellValue());
				}

			
			}
			}
			list.add(map);
			}
			
			
			List<Map<Integer,String>> cpbhlist = new ArrayList<Map<Integer,String>>();
			//进入判断
			int flag = 1;//判断取出的数据是否正确，正确是1 错误是0
			for(Map<Integer,String> map:list) { // 遍历取出的数据
				
			
				
				//判断姓名是否为空
				if (map.get(0)!=null&&!map.get(0).equals("")) {
				String name = map.get(0);
				if(name!=null&&!name.equals("")){
					String sql = "select * FROM sb_customer sc WHERE sc.`name` =? AND sc.organIds = ? and sc.dataStatus in(1,2)";
					if(Db.findFirst(sql,name,organIds)!=null){
						json.put("message",map.get(0)+"名字重复，请更改");
						flag = 0;
						break;
					}
				}
					
				}else{
					json.put("message","顾客姓名不能为空，请检查顾客姓名或是否有空行");
					flag = 0;
					break;
				}
				
				//判断手机号是否正确
				if (map.get(1)!=null&&!map.get(1).equals("")&&map.get(1).length()==11){
					String phone = map.get(1);
					if(phone!=null&&!phone.equals("")){
						String sql = "select * FROM sb_customer sc WHERE sc.phone = ? AND sc.organIds = ?  and sc.dataStatus in(1,2)";
						if(Db.findFirst(sql,phone,organIds)!=null){
							json.put("message",map.get(0)+"手机号已存在");
							flag = 0;
							break;
						}
					}
				}else{
					json.put("message","请检查"+map.get(0)+"的手机号");
					flag = 0;
					break;
				}
				
				
				//判断年龄是否正确
				if (map.get(2)!=null&&!map.get(2).equals("")){
					int age;
					try {
						age = Integer.parseInt(map.get(2));
						System.out.println(age);
						if(age<1||age>100){
							json.put("message","请检查"+map.get(0)+"的年龄是否在1-100之间");
							flag = 0;
							break;
						}
					} catch (NumberFormatException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						json.put("message",map.get(0)+"的年龄格式不正确");
						flag = 0;
						break;
					}
					
				}else{
					json.put("message",map.get(0)+"的年龄不能为空");
					flag = 0;
					break;
				}
				
				//判断身高是否正确
				if (map.get(3)!=null&&!map.get(3).equals("")){
				
					int height;
					try {
						height = Integer.parseInt(map.get(3));
						System.out.println(height);
						if(height<100||height>200){
							json.put("message","请检查"+map.get(0)+"的身高是否在100-220之间");
							flag = 0;
							break;
						}else{
							//判断体重是否正确
							if (map.get(4)!=null&&!map.get(4).equals("")){
								float weight;
								try {
									weight = Float.parseFloat(map.get(4));
									System.out.println(weight);
									if(weight<60||weight>500){
										json.put("message","请检查"+map.get(0)+"的体重是否在60-500之间");
										flag = 0;
										break;
									}else{
										//判断性别是否正确
										if (map.get(5)!=null&&!map.get(5).equals("")){
											String sex = map.get(5);
											if(sex.equals("男")||sex.equals("女")){
												System.out.println(map.get(5));
												float stdWeight = getStdWeight(map.get(5), height,Integer.parseInt(map.get(2)));
												if (stdWeight != 0) {
													System.out.println(stdWeight);
												}else{
													json.put("message",map.get(0)+"标体测算失败，请检查性别、年龄、身高");
													flag = 0;
													break;
												}
												
											}else{
												json.put("message",map.get(0)+"性别错误");
												flag = 0;
												break;
											}
										}else{
											json.put("message",map.get(0)+"性别不能为空");
											flag = 0;
											break;
										}
									}
								} catch (NumberFormatException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
									json.put("message",map.get(0)+"的体重格式不正确");
									flag = 0;
									break;
								}
								
							}else{
								json.put("message",map.get(0)+"的体重不能为空");
								flag = 0;
								break;
							}
							
							
							
						}
					} catch (NumberFormatException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						json.put("message",map.get(0)+"的身高格式不正确");
						flag = 0;
						break;
					}
					
				}else{
					json.put("message",map.get(0)+"的身高不能为空");
					flag = 0;
					break;
				}
				
				
				
			
				
				//判断身份证号是否正确
				if (map.get(6)!=null&&!map.get(6).equals("")){
					String idString = map.get(6);
					if (idString.length()==18) {
						System.out.println(idString);
					}else{
						json.put("message","请检查"+map.get(0)+"的身份证号");
						flag = 0;
						break;
					}
				}
				
				//判断进店时间是否正确
				if (map.get(8)!=null&&!map.get(8).equals("")){
					String dateStr = map.get(8);
					SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
					try {
						Date date=sdf.parse(dateStr);
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						json.put("message","请检查"+map.get(0)+"的进店时间，正确格式应如2017-1-1");
						flag = 0;
						break;
					}
				}else{
					json.put("message",map.get(0)+"的进店时间不能为空");
					flag = 0;
					break;
				}
				
				//判断目标体重是否正确
				if (map.get(9)!=null&&!map.get(9).equals("")){
					float weight;
					try {
						weight = Float.parseFloat(map.get(9));
						System.out.println(weight);
						if(weight<60||weight>500){
							json.put("message","请检查"+map.get(0)+"的目标体重是否在60-500之间");
							flag = 0;
							break;
						}
					} catch (NumberFormatException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						json.put("message",map.get(0)+"的目标体重格式不正确");
						flag = 0;
						break;
					}
					
				}else{
					json.put("message",map.get(0)+"的目标体重不能为空");
					flag = 0;
					break;
				}
				
				//判断疗程是否正确
				if (map.get(10)!=null&&!map.get(10).equals("")){
					String lc = map.get(10);
					if(lc!=null&&!lc.equals("")){
						String sql = "SELECT ids FROM sb_product sp WHERE sp.name = ?";
						if(Db.findFirst(sql,lc)==null){
							json.put("message",map.get(0)+"的疗程名称不正确");
							flag = 0;
							break;
						}else{
							String lcIds = Db.findFirst(sql,lc).getStr("ids");
							
							//判断疗程数是否正确
							if (map.get(11)!=null&&!map.get(11).equals("")){
								int lcs;
								try {
									lcs = Integer.parseInt(map.get(11));
									if(lcIds.equals("4777c2c215b6408ab13c1eac4190ce46")){
										if(lcs!=1){
											json.put("message",map.get(0)+"的疗程为单疗程，请将疗程数设置为1");
											flag = 0;
											break;
										}
										if(map.get(13)!=null&&!map.get(13).equals("")){
											json.put("message",map.get(0)+"的疗程为单疗程，请删除其总目标或更改疗程");
											flag = 0;
											break;
										}
//										if(map.get(23)!=null&&!map.get(23).equals("")){
//											json.put("message",map.get(0)+"的疗程为单疗程，请删除其减重周期或更改疗程");
//											flag = 0;
//											break;
//										}
										
										String sycs = map.get(23);
										if(sycs!=null&&!sycs.equals("")){
										System.out.println(sycs);
										}else{
											json.put("message",map.get(0)+"的疗程为单疗程，请数入他的单疗程剩余次数");
											flag = 0;
											break;
										}
									}
									else if(lcIds.equals("27aeb2d41d044394b9b58f6814baa4fa")){
										if(lcs!=1){
											json.put("message",map.get(0)+"的疗程为一疗程带售后，请将疗程数设置为1");
											flag = 0;
											break;
										}
										
										
										
										
									}else{
										
										//判断消费金额是否正确
										if (map.get(12)!=null&&!map.get(12).equals("")){
											float cost;
											try {
												cost = Float.parseFloat(map.get(12));
												System.out.println(cost);
												if(cost<0||cost>1000000){
													json.put("message","请检查"+map.get(0)+"的消费金额是否在0-1000000之间");
													flag = 0;
													break;
												}
											} catch (NumberFormatException e) {
												// TODO Auto-generated catch block
												e.printStackTrace();
												json.put("message",map.get(0)+"的消费金额格式不正确");
												flag = 0;
												break;
											}
											
										}else{
											json.put("message",map.get(0)+"的消费金额不能为空");
											flag = 0;
											break;
										}
										
										//判断总目标是否正确
										if (map.get(13)!=null&&!map.get(13).equals("")){
											int target;
											try {
												target = Integer.parseInt(map.get(13));
												System.out.println(target);
												if(target<0||target>50){
													json.put("message","请检查"+map.get(0)+"的总目标是否在0-50之间");
													flag = 0;
													break;
												}
											} catch (NumberFormatException e) {
												// TODO Auto-generated catch block
												e.printStackTrace();
												json.put("message",map.get(0)+"的总目标格式不正确");
												flag = 0;
												break;
											}
											
										}else{
											json.put("message",map.get(0)+"的总目标不能为空");
											flag = 0;
											break;
										}
										
//										//判断减重周期是否正确
//										if (map.get(23)!=null&&!map.get(23).equals("")){
//											int jzzq;
//											try {
//												jzzq = Integer.parseInt(map.get(23));
//											
//												if(jzzq<0||jzzq>100){
//													json.put("message","请检查"+map.get(0)+"的减重周期是否在0-100之间");
//													flag = 0;
//													break;
//												}
//											} catch (NumberFormatException e) {
//												// TODO Auto-generated catch block
//												e.printStackTrace();
//												json.put("message",map.get(0)+"的减重周期格式不正确");
//												flag = 0;
//												break;
//											}
//											
//										}else{
//											json.put("message",map.get(0)+"的减重周期不能为空");
//											flag = 0;
//											break;
//										}
//										
									}
									System.out.println(lcs);
									if(lcs<0||lcs>50){
										json.put("message","请检查"+map.get(0)+"的疗程数是否在0-50之间");
										flag = 0;
										break;
									}
								} catch (NumberFormatException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
									json.put("message",map.get(0)+"的疗程数格式不正确");
									flag = 0;
									break;
								}
								
							}else{
								json.put("message","请输入"+map.get(0)+"的疗程数，或删除其疗程");
								flag = 0;
								break;
							}
							
						
							//System.out.println(lcIds);
						}
					}
				}else{
					if(map.get(11)!=null&&!map.get(11).equals("")){
						json.put("message",map.get(0)+"的疗程为空，请删除其疗程数或添加疗程");
						flag = 0;
						break;
					}
					if(map.get(12)!=null&&!map.get(12).equals("")){
						json.put("message",map.get(0)+"的疗程为空，请删除其消费金额或添加疗程");
						flag = 0;
						break;
					}
					if(map.get(13)!=null&&!map.get(13).equals("")){
						json.put("message",map.get(0)+"的疗程为空，请删除其总目标或添加疗程");
						flag = 0;
						break;
					}
//					if(map.get(23)!=null&&!map.get(23).equals("")){
//						json.put("message",map.get(0)+"的疗程为空，请删除其减重周期或添加疗程");
//						flag = 0;
//						break;
//					}
					
					
				}
				
//				//产品编号是否存在
//				if (map.get(22)!=null&&!map.get(22).equals("")){
//					String cpbh = map.get(22);
//						if(cpbh!=null&&!cpbh.equals("")){
//							String sql1 = " select productNo from  sb_customer_detail  where dataStatus in ('1','2') and organIds = ? and  productNo = ?";
//							List<Record> cbis = Db.find(sql1,organIds,cpbh);
//							if(cbis==null||cbis.size()==0){
//								cpbhlist.add(map);
//							}else{
//								json.put("message",map.get(0)+"的产品编号已经存在，请重新添加");
//								flag = 0;
//								break;
//							}
//							}
//				}
				
				//判断减重周期是否正确
				if (map.get(13)!=null&&!map.get(13).equals("")){
					int lcs;
					try {
						lcs = Integer.parseInt(map.get(13));
						System.out.println(lcs);
						if(lcs<0||lcs>100){
							json.put("message","请检查"+map.get(0)+"的减重周期是否在0-100之间");
							flag = 0;
							break;
						}
					} catch (NumberFormatException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						json.put("message",map.get(0)+"的减重周期格式不正确");
						flag = 0;
						break;
					}
					
				}
				
				//判断消费金额是否正确
				if (map.get(12)!=null&&!map.get(12).equals("")){
					float cost;
					try {
						cost = Float.parseFloat(map.get(12));
						System.out.println(cost);
						if(cost<0||cost>1000000){
							json.put("message","请检查"+map.get(0)+"的消费金额是否在0-1000000之间");
							flag = 0;
							break;
						}
					} catch (NumberFormatException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						json.put("message",map.get(0)+"的消费金额格式不正确");
						flag = 0;
						break;
					}
					
				}
				
				//判断总目标是否正确
				if (map.get(13)!=null&&!map.get(13).equals("")){
					int target;
					try {
						target = Integer.parseInt(map.get(13));
						System.out.println(target);
						if(target<0||target>50){
							json.put("message","请检查"+map.get(0)+"的总目标是否在0-50之间");
							flag = 0;
							break;
						}
					} catch (NumberFormatException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						json.put("message",map.get(0)+"的总目标格式不正确");
						flag = 0;
						break;
					}
					
				}
				
				
				//判断出生日期是否正确
				if (map.get(14)!=null&&!map.get(14).equals("")){
					String dateStr = map.get(14);
					SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
					try {
						Date date=sdf.parse(dateStr);
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						json.put("message","请检查"+map.get(0)+"的出生日期，正确格式应如2017-1-1");
						flag = 0;
						break;
					}
				}
				
				
				//判断进店方式是否正确
				if (map.get(15)!=null&&!map.get(15).equals("")){
					String jdfs = map.get(15);
					if(jdfs!=null&&!jdfs.equals("")){
						String sql = "SELECT ids FROM sys_code sc WHERE sc.`name` = ?";
						if(Db.findFirst(sql,jdfs)==null){
							json.put("message",map.get(0)+"的进店方式输入不正确");
							flag = 0;
							break;
						}else{
							String lcIds = Db.findFirst(sql,jdfs).getStr("ids");
							System.out.println(lcIds);
						}
					}
				}
				
				
				//判断省份是否正确
				if (map.get(16)!=null&&!map.get(16).equals("")){
					String province = map.get(16);
					if(province!=null&&!province.equals("")){
						String sql = "SELECT ids FROM sys_code sc WHERE sc.`name` = ?";
						if(Db.findFirst(sql,province)==null){
							json.put("message",map.get(0)+"的省份输入不正确");
							flag = 0;
							break;
						}else{
							String lcIds = Db.findFirst(sql,province).getStr("ids");
							System.out.println(lcIds);
						}
					}
				}
				
				

				//判断市是否正确
				if (map.get(17)!=null&&!map.get(17).equals("")){
					String city = map.get(17);
					if(city!=null&&!city.equals("")){
						String sql = "SELECT ids FROM sys_code sc WHERE sc.`name` = ?";
						if(Db.findFirst(sql,city)==null){
							json.put("message",map.get(0)+"的市输入不正确");
							flag = 0;
							break;
						}else{
							String lcIds = Db.findFirst(sql,city).getStr("ids");
							System.out.println(lcIds);
						}
					}
				}
				
				
				//判断区是否正确
				if (map.get(18)!=null&&!map.get(18).equals("")){
					String area = map.get(18);
					if(area!=null&&!area.equals("")){
						String sql = "SELECT ids FROM sys_code sc WHERE sc.`name` = ?";
						if(Db.findFirst(sql,area)==null){
							json.put("message",map.get(0)+"的区输入不正确");
							flag = 0;
							break;
						}else{
							String lcIds = Db.findFirst(sql,area).getStr("ids");
							System.out.println(lcIds);
						}
					}
				}
				
				
				//判断负责人是否正确
				if (map.get(21)!=null&&!map.get(21).equals("")){
					String fzr = map.get(21);
					if(fzr!=null&&!fzr.equals("")){
						String sql = "SELECT ids FROM sys_user sc WHERE sc.`name` = ? AND sc.organizationids =?";
						if(Db.findFirst(sql,fzr,organIds)==null){
							json.put("message",map.get(0)+"的负责人输入不正确，请核对姓名");
							flag = 0;
							break;
						}else{
							String lcIds = Db.findFirst(sql,fzr,organIds).getStr("ids");
							System.out.println(lcIds);
						}
					}
				}else{
					json.put("message",map.get(0)+"的负责人不能为空");
					flag = 0;
					break;
				}
				
				
				//判断单疗程剩余次数是否正确
				if (map.get(23)!=null&&!map.get(23).equals("")){
					
					if (map.get(10)!=null&&!map.get(10).equals("")){
						String lc = map.get(10);
						if(lc!=null&&!lc.equals("")){
							String sql = "SELECT ids FROM sb_product sp WHERE sp.name = ?";
							if(Db.findFirst(sql,lc)==null){
								json.put("message",map.get(0)+"的疗程名称不正确，请修改为单疗程");
								flag = 0;
								break;
							}else if(Db.findFirst(sql,lc).getStr("ids").equals("4777c2c215b6408ab13c1eac4190ce46")){
								String lcIds = Db.findFirst(sql,lc).getStr("ids");
								System.out.println(lcIds);
								
								int rest;
								try {
									rest = Integer.parseInt(map.get(23));
									System.out.println(rest);
									if(rest<0||rest>20){
										json.put("message","请检查"+map.get(0)+"的单疗程剩余次数是否在0-20之间");
										flag = 0;
										break;
									}
								} catch (NumberFormatException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
									json.put("message",map.get(0)+"的单疗程剩余次数格式不正确，请输入0-20的整数");
									flag = 0;
									break;
								}
								
							}
							else{
								json.put("message",map.get(0)+"的疗程名称不正确，请修改为单疗程");
								flag = 0;
								break;
							}
						}
					}else{
						json.put("message",map.get(0)+"的疗程不是单疗程，请不要添加单疗程剩余次数或将其疗程填为单疗程");
						flag = 0;
						break;
					}
					
				}
				
				
				}
			
			
			
			//如果通过验证，保存数据
			if(flag==1){
				for(Map<Integer,String> map:list) { // 遍历取出的数据，并保存
					
					//保存顾客信息
					Customer customer = new Customer();
					CustomerDetail customerDetail = new CustomerDetail();
					CustomerAgreement customerAgreement = new CustomerAgreement();
					Temporary temporary = new Temporary();
					CustomerProduct customerProduct = new CustomerProduct();
					
					customer.set(Customer.column_organIds, organIds);
					customerDetail.set(CustomerDetail.column_organIds, organIds);
					customerAgreement.set(CustomerAgreement.column_organIds, organIds);
					temporary.set(Temporary.column_organIds, organIds);
					
					//判断 map.get(0)是否为空，格式是否正确
					if (map.get(0)!=null&&!map.get(0).equals("")) {
						customer.set(Customer.column_name, map.get(0));
						temporary.set(Temporary.column_name, map.get(0));
					}
//--------------------------------------------------------------------------------------------------------------------					
					//设置手机号、用户名、密码、盐
					if (map.get(1)!=null&&!map.get(1).equals("")&&map.get(1).length()==11) {
						customer.set(Customer.column_phone, map.get(1));
						customer.set(Customer.column_userName,map.get(1));
						temporary.set(Temporary.column_phone, map.get(1));
						customerDetail.set(CustomerDetail.column_username,map.get(1));
						try {
							byte[] salt = ToolPbkdf2.generateSalt();// 密码盐
							byte[] encryptedPassword = ToolPbkdf2.getEncryptedPassword("123456", salt);
							customer.set(Customer.column_salt, Base64.encodeBase64String(salt));
							customer.set(Customer.column_password, Base64.encodeBase64String(encryptedPassword));
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
//--------------------------------------------------------------------------------------------------------------------
					//设置会员编号
					String chybh = "000001";
					Map<String, Object> param = new HashMap<String, Object>();
					param.put("column", Customer.column_organIds);
					String sql = getSqlByBeetl(Customer.sqlId_column, param);
					List<Customer> clist = Customer.dao.find(sql, organIds);
					ArrayList<Integer> numList = new ArrayList<Integer>();
					if (clist != null && clist.size() > 0) {
						for (Customer cuss : clist) {
							String hybh = cuss.getStr(Customer.column_hybh);
							int n = Integer.parseInt(hybh);
							numList.add(n);
						}
						int a = Collections.max(numList);
						chybh = String.format("%06d", a + 1);
					}
					
					customer.set(Customer.column_hybh, chybh);
//--------------------------------------------------------------------------------------------------------------------
					
					
					
					if(map.get(2)!=null&&!map.get(2).equals("")){
						int age;
						try {
							age = Integer.parseInt(map.get(2));
							customer.set(Customer.column_age, age);
							customerDetail.set(CustomerDetail.column_age, age);
							temporary.set(Temporary.column_age, age);
						} catch (NumberFormatException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							
						}
						
					}
					
					if(map.get(5)!=null&&!map.get(5).equals("")){
						customer.set(Customer.column_sex, map.get(5));
						customerDetail.set(CustomerDetail.column_sex, map.get(5));
					}
					if(map.get(6)!=null&&!map.get(6).equals("")){
						customer.set(Customer.column_sfzmhm, map.get(6));
						customerDetail.set(CustomerDetail.column_sfzmhm, map.get(6));
					}
					if(map.get(7)!=null&&!map.get(7).equals("")){
						customer.set(Customer.column_email, map.get(7));
					}
					
					if(map.get(8)!=null&&!map.get(8).equals("")){
						String dateStr = map.get(8);
						SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
						Date date;
						try {
							date = sdf.parse(dateStr);
							customer.set(Customer.column_registtime,date);
						} catch (ParseException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
					}
					customer.set(Customer.column_createDate, new Date())
					.set(Customer.column_createId, userIds)
					.set(Customer.column_state, "1")
					.set(Customer.column_dataStatus, 2);
					if (!customer.save()) {
						log.debug("顾客信息保存失败！！");
						throw new RuntimeException("顾客信息保存失败!");
					}else{
						
					
//---------------------------------------------------------------------------------------------------------------					
					//保存顾客详细信息
						int treatment = 0;
						if(map.get(11)!=null&&!map.get(11).equals("")){
							treatment = Integer.parseInt(map.get(11));
								if(treatment<0||treatment>50){
									treatment = 0;
								}
							}
					customerDetail.set(CustomerDetail.column_customerIds, customer.getStr(customer.column_ids))
					.set(CustomerDetail.column_sjtreatment, treatment+"");
					customerDetail.set(CustomerDetail.column_organName, organName);
					if(map.get(3)!=null&&!map.get(3).equals("")){
						int height;
						try {
							height = Integer.parseInt(map.get(3));
							customerDetail.set(CustomerDetail.column_height,height);
							temporary.set(Temporary.column_height, height);
							float stdWeight = getStdWeight(map.get(5), height,Integer.parseInt(map.get(2)));
							if (stdWeight != 0) {
								customerDetail.set(CustomerDetail.column_standardWeight,stdWeight);
							}
						} catch (NumberFormatException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							
						}
						
					}
					if(map.get(4)!=null&&!map.get(4).equals("")){
						float weight;
						try {
							weight = Float.parseFloat(map.get(4));
							customerDetail.set(CustomerDetail.column_firstWeight, weight);
							customerDetail.set(CustomerDetail.column_nowWeight,weight);
							customerDetail.set(CustomerDetail.column_minWeight,weight);
							temporary.set(Temporary.column_weight, weight);
							if(map.get(9)!=null&&!map.get(9).equals("")){
								float targetWeight;
								try {
									targetWeight = Float.parseFloat(map.get(9));
									customerDetail.set(CustomerDetail.column_targetWeight,targetWeight);
									float delWeight = weight-targetWeight;
									customerDetail.set(CustomerDetail.column_delWeight,delWeight);
									
								} catch (NumberFormatException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
									
								}
								
							}
						} catch (NumberFormatException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							
						}
					
					}
					if(map.get(8)!=null&&!map.get(8).equals("")){
						String dateStr = map.get(8);
						SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
						Date date;
						try {
							date = sdf.parse(dateStr);
							customerDetail.set(CustomerDetail.column_firstDate,date);
							customerDetail.set(CustomerDetail.column_toStoreDate,date);
							customerDetail.set(CustomerDetail.column_minDate,date);
							temporary.set(Temporary.column_gxsj, date);
						} catch (ParseException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					
					if(map.get(14)!=null&&!map.get(14).equals("")){
						String dateStr = map.get(14);
						SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
						Date date;
						try {
							date = sdf.parse(dateStr);
							customerDetail.set(CustomerDetail.column_birth,date);
						} catch (ParseException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				
						
					
					if(map.get(15)!=null&&!map.get(15).equals("")){
						String jdfs = map.get(15);
						if(jdfs!=null&&!jdfs.equals("")){
							String sqljdfs = "SELECT ids FROM sys_code sc WHERE sc.`name` = ?";
							if(Db.findFirst(sqljdfs,jdfs)==null){
								json.put("message",map.get(0)+"的进店方式输入不正确");
								flag = 0;
								break;
							}else{
								String lcIds = Db.findFirst(sqljdfs,jdfs).getStr("ids");
								customerDetail.set(CustomerDetail.column_type,lcIds);
							}
						}
					
					}
					//省份
					if(map.get(16)!=null&&!map.get(16).equals("")){
						String jdfs = map.get(16);
						if(jdfs!=null&&!jdfs.equals("")){
							String sqljdfs = "SELECT ids FROM sys_code sc WHERE sc.`name` = ?";
							if(Db.findFirst(sqljdfs,jdfs)==null){
								json.put("message",map.get(0)+"的省份输入不正确");
								flag = 0;
								break;
							}else{
								String lcIds = Db.findFirst(sqljdfs,jdfs).getStr("ids");
								customerDetail.set(CustomerDetail.column_provice,lcIds);
							}
						}
					
					}
					
					//市
					if(map.get(17)!=null&&!map.get(17).equals("")){
						String jdfs = map.get(17);
						if(jdfs!=null&&!jdfs.equals("")){
							String sqljdfs = "SELECT ids FROM sys_code sc WHERE sc.`name` = ?";
							if(Db.findFirst(sqljdfs,jdfs)==null){
								json.put("message",map.get(0)+"的省份输入不正确");
								flag = 0;
								break;
							}else{
								String lcIds = Db.findFirst(sqljdfs,jdfs).getStr("ids");
								customerDetail.set(CustomerDetail.column_city,lcIds);
							}
						}
					
					}
					
					//区
					if(map.get(18)!=null&&!map.get(18).equals("")){
						String jdfs = map.get(18);
						if(jdfs!=null&&!jdfs.equals("")){
							String sqljdfs = "SELECT ids FROM sys_code sc WHERE sc.`name` = ?";
							if(Db.findFirst(sqljdfs,jdfs)==null){
								json.put("message",map.get(0)+"的省份输入不正确");
								flag = 0;
								break;
							}else{
								String lcIds = Db.findFirst(sqljdfs,jdfs).getStr("ids");
								customerDetail.set(CustomerDetail.column_area,lcIds);
							}
						}
					
					}
					
					if(map.get(19)!=null&&!map.get(19).equals("")){
						customerDetail.set(CustomerDetail.column_address,map.get(19));
					}
					
					if(map.get(20)!=null&&!map.get(20).equals("")){
						customerDetail.set(CustomerDetail.column_job,map.get(20));
					}
					if(map.get(21)!=null&&!map.get(21).equals("")){
						String fzr = map.get(21);
						if(fzr!=null&&!fzr.equals("")){
							String sqlFzr = "SELECT ids FROM sys_user sc WHERE sc.`name` = ? AND sc.organizationids =?";
							if(Db.findFirst(sqlFzr,fzr,organIds)!=null){
								String fzrIds = Db.findFirst(sqlFzr,fzr,organIds).getStr("ids");
								customerDetail.set(CustomerDetail.column_chargePersion,fzrIds);
							}
						}
					}
					
//					if(map.get(22)!=null&&!map.get(22).equals("")){
//						customerDetail.set(CustomerDetail.column_productNo,map.get(22));
//					}
//					
					if(map.get(22)!=null&&!map.get(22).equals("")){
						customerDetail.set(CustomerDetail.column_benhao,map.get(22));
					}
					
					if(map.get(10)!=null&&!map.get(10).equals("")){
						String lc = map.get(10);
						if(lc!=null&&!lc.equals("")){
						String sqllc = "SELECT ids FROM sb_product sp WHERE sp.name = ?";
						if(Db.findFirst(sqllc,lc)==null){
							json.put("message",map.get(0)+"的疗程名称不正确");
							flag = 0;
							break;
						}else{
							customerDetail.set(CustomerDetail.column_customerType, "0");
							}
						}
					}else{
						customerDetail.set(CustomerDetail.column_customerType, "1");
					}
					
					
					customerDetail.set(CustomerDetail.column_hybh,customer.getStr(Customer.column_hybh))
					.set(CustomerDetail.column_phone, customer.getStr(Customer.column_phone))
					.set(CustomerDetail.column_name,  customer.getStr(Customer.column_name))
					.set(CustomerDetail.column_createId, userIds)
					.set(CustomerDetail.column_createDate, new Date())
					.set(CustomerDetail.column_dataStatus, 2);

					
//----------------------------------------------------------------------------------------------------------------					s
					/**
					 * 保存总目标
					 */
					// 根据减重周期求出结束的日期
					String zmb = map.get(13);
					String lcsstr = map.get(11);
					String str = "";
					if(zmb!=null&&!zmb.equals("")){
						 str = zmb;
					}else{
						if(lcsstr!=null&&!lcsstr.equals("")){
							str = lcsstr;
						}
					}
					
					
					if(str!=null&&!str.equals("")){
					
						int lcs;
						try {
							lcs = Integer.parseInt(str);
							if(lcs>=0&&lcs<=50){
								Date date = customerDetail.getDate(CustomerDetail.column_firstDate);
								Calendar cal = Calendar.getInstance();
								cal.setTime(date);
								cal.add(cal.MONTH, lcs);
								SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd HH:mm");
								String lastMonth = dft.format(cal.getTime());
								
								 float weight = Float.parseFloat(map.get(4));
								 float targetWeight =  Float.parseFloat(map.get(9));
								 float delWeight = weight-targetWeight;
								// 保存总目标汇总表
								DelWeiTargetSum delWeiT = new DelWeiTargetSum();
								delWeiT.set(DelWeiTargetSum.column_targetName, "总目标")
										.set(DelWeiTargetSum.column_delWei, delWeight).set(DelWeiTargetSum.column_targetWei, targetWeight)
										.set(DelWeiTargetSum.column_customerIds, customer.getStr(Customer.column_ids))
										.set(DelWeiTargetSum.column_startWei, weight)
										.set(DelWeiTargetSum.column_createId, userIds).set(DelWeiTargetSum.column_createDate, new Date())
										.set(DelWeiTargetSum.column_startTime, date)
										.set(DelWeiTargetSum.column_dataStatus, 2)
										.set(DelWeiTargetSum.column_endTime, lastMonth);
										

								if (!delWeiT.save()) {
									log.debug("顾客总目标信息保存失败！");
									throw new RuntimeException("顾客总目标信息保存失败");
								}
								
							}
						} catch (NumberFormatException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							
						}
						
					
					}
					
					/**
					 * 保存协议
					 */
					/*int treatment = 0;
					if(map.get(11)!=null&&!map.get(11).equals("")){
						treatment = Integer.parseInt(map.get(11));
							if(treatment<0||treatment>50){
								treatment = 0;
							}
						}*/
					
					// 通过当前机构id获取机构编码
					String cuoBh = BentryRegisterService.getOrgBh(organIds);

					
					// 获取编号
					String bh = BentryRegisterService.getBH(cuoBh,treatment,chybh,customerDetail.getDate(CustomerDetail.column_firstDate));
					if( map.get(12)!=null&& !map.get(12).equals("")){
						customerAgreement.set(CustomerAgreement.column_cost, map.get(12));
					}else{
						customerAgreement.set(CustomerAgreement.column_cost, 0);
					}
					
					if(map.get(10)!=null&&!map.get(10).equals("")){
						
						String lc = map.get(10);
						if(lc!=null&&!lc.equals("")){
							String sqllc = "SELECT ids FROM sb_product sp WHERE sp.name = ?";
							if(Db.findFirst(sqllc,lc)==null){
								json.put("message",map.get(0)+"的疗程名称不正确");
								flag = 0;
								break;
							}else{
								customerAgreement.set(CustomerAgreement.column_codeIds,Db.findFirst(sqllc,lc).get("ids"));
							}
						}
					}
					// 根据减重周期求出结束的日期
					String zmb1 = map.get(13);
					String lcsstr1 = map.get(11);
					String str1 = "";
					if(zmb1!=null&&!zmb1.equals("")){
						 str1 = zmb1;
					}else{
						if(lcsstr1!=null&&!lcsstr1.equals("")){
							str1 = lcsstr1;
						}
					}
					if(str1!=null&&!str1.equals("")){
						int jzzq = Integer.parseInt(str1);
						customerAgreement.set(CustomerAgreement.column_target,jzzq);
					}
					
					customerAgreement.set(CustomerAgreement.column_customerID, customer.getStr(Customer.column_ids))
							.set(CustomerAgreement.column_organIds, organIds).set(CustomerAgreement.column_bh, bh)
							.set(CustomerAgreement.column_before_weight, customerDetail.getFloat(CustomerDetail.column_firstWeight))
							.set(CustomerAgreement.column_after_weight, customerDetail.getFloat(CustomerDetail.column_targetWeight)).set(CustomerAgreement.column_isPay, "1")
							.set(CustomerAgreement.column_createId, userIds).set(CustomerAgreement.column_createDate, new Date())
							.set(CustomerAgreement.column_dataStatus, 2)
							.set(CustomerAgreement.column_treatment, treatment)
							
							.set(CustomerAgreement.column_std_weight,customerDetail.getFloat(CustomerDetail.column_standardWeight))
							.set(CustomerAgreement.column_time,customerDetail.getDate(CustomerDetail.column_firstDate)).set(CustomerAgreement.column_state, "1");

					if (!customerAgreement.save()) {
						log.debug("顾客协议保存失败！！");
						throw new RuntimeException("顾客协议保存失败!");
					}
					customerDetail.set(CustomerDetail.column_agreementIds, customerAgreement.getStr(CustomerAgreement.column_ids))
					.set(CustomerDetail.column_agreementBH, bh)
					.set(CustomerDetail.column_treatmentName, customerAgreement.getStr(CustomerAgreement.column_codeIds));
					
					if (!customerDetail.save()) {
						log.debug("顾客详细信息保存失败！！");
						throw new RuntimeException("顾客详细信息保存失败!");
					}
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------------				
		/**
		 * 保存疗程信息及单疗程剩余信息			
		 */
					if(map.get(10)!=null&&!map.get(10).equals("")){
						
						String lc1 = map.get(10);
						if(lc1!=null&&!lc1.equals("")){
							String sqllc = "SELECT ids FROM sb_product sp WHERE sp.name = ?";
							if(Db.findFirst(sqllc,lc1)==null){
								json.put("message",map.get(0)+"的疗程名称不正确");
								flag = 0;
								break;
							}else{
								String lcIds = Db.findFirst(sqllc,lc1).getStr("ids");
								Product p = Product.dao.findById(lcIds);
								String sqllcjg = "SELECT spp.outPrice FROM sb_product sp LEFT JOIN sys_code sc ON sp.typeIds = sc.ids LEFT JOIN sb_product_price spp LEFT JOIN  sys_organization so on spp.priceIds=so.priceIds on  sp.ids=spp.productIds WHERE  sp.`status`='1' AND  spp.`status`='1' and  sp.ids = ?   and  so.ids=?";
								if(Db.findFirst(sqllcjg,lcIds,organIds)!=null){
								float proUnitPrice = Db.findFirst(sqllcjg,lcIds,organIds).getFloat("outPrice");
								customerProduct.set(CustomerProduct.column_proUnitPrice, proUnitPrice);
								}
								
								
								// 购买的产品总容量
								float capacities = Float.parseFloat(map.get(11))
										* Integer.parseInt(p.getStr(Product.column_proCapacity));
								// 购买的产品总经验值
								//单疗程
								
									float totalException = Float.parseFloat(map.get(11))* Integer.parseInt(p.getStr(Product.column_proExperience)==null?"0":p.getStr(Product.column_proExperience));
									if(lcIds.equals("4777c2c215b6408ab13c1eac4190ce46")){
										 totalException = Float.parseFloat(map.get(23));
									}
								// 保存顾客产品记录
								customerProduct.set(CustomerProduct.column_organids, organIds)
										.set(CustomerProduct.column_customerID, customer.getStr(Customer.column_ids))
										.set(CustomerProduct.column_productID, lcIds)
										.set(CustomerProduct.column_count, Integer.parseInt(map.get(11)))
										
										.set(CustomerProduct.column_capacity, p.getStr(Product.column_proSpecification))
										.set(CustomerProduct.column_capacities, capacities)
										.set(CustomerProduct.column_proExperience, p.getStr(Product.column_proExperience))
										.set(CustomerProduct.column_totalExperience, totalException)
										//.set(CustomerProduct.column_yxDate, yxDate)
										.set(CustomerProduct.column_dataStatus, 2)
										
										.set(CustomerProduct.column_updateDate, new Date());
								if (!customerProduct.save()) {
									log.debug("保存顾客产品失败！！");
									throw new RuntimeException("保存顾客产品失败!");
								}
								
								//保存顾客产品明细
								CustomerProductSurplus  cusprosur=new CustomerProductSurplus();
								cusprosur.set(CustomerProductSurplus.column_organIds, organIds)
										.set(CustomerProductSurplus.column_customerIds, customer.getStr(Customer.column_ids))
										.set(CustomerProductSurplus.column_productIds,lcIds)
										.set(CustomerProductSurplus.column_count,Integer.parseInt(map.get(11)))
										.set(CustomerProductSurplus.column_proExperience,  p.getStr(Product.column_proExperience))
										.set(CustomerProductSurplus.column_totalExperience, totalException)
										.set(CustomerProductSurplus.column_dataStatus, 2)
										.set(CustomerProductSurplus.column_gxsj, new Date());
								if (!cusprosur.save()) {
									log.debug("保存顾客产品明细失败！！");
									throw new RuntimeException("保存顾客产品明细失败!");
								}
							}
						
								
							}
							
					}
					
	//----------------------------------------------------------------------------------------------------------------------------------------------------------------------------				
	/**
	 * 保存测算信息				
	 */
					int jzzq = 0;
					if(map.get(13)!=null&&!map.get(13).equals("")){
						jzzq = Integer.parseInt(map.get(13));
					 }
					
					if(map.get(12)!=null&&!map.get(12).equals("")){
						float cost = Float.parseFloat(map.get(12));
						temporary.set(CollectionTemporary.column_cost,cost);
					 }
					if(map.get(5)!=null&&!map.get(5).equals("")){
						
						temporary.set(CollectionTemporary.column_sex,map.get(5));
					 }
					
					
					temporary.set(CollectionTemporary.column_treatment, treatment + "")
					.set(CollectionTemporary.column_standWeight,customerDetail.getFloat(CustomerDetail.column_standardWeight))
					.set(CollectionTemporary.column_targetWeight, customerDetail.getFloat(CustomerDetail.column_targetWeight))
					.set(CollectionTemporary.column_delWeight, customerDetail.getFloat(CustomerDetail.column_delWeight))
					.set(CollectionTemporary.column_weightDay,jzzq)
					.set(CollectionTemporary.column_jdfs,customerDetail.getStr(CustomerDetail.column_type))
					/*.set(CollectionTemporary.column_jsrIds, temp.getStr(CollectionTemporary.column_jsrIds))
					.set(CollectionTemporary.column_jsrName, temp.getStr(CollectionTemporary.column_jsrName))
					.set(CollectionTemporary.column_jsrorg, temp.getStr(CollectionTemporary.column_jsrorg))
					.set(CollectionTemporary.column_jsrPhone, temp.getStr(CollectionTemporary.column_jsrPhone))
					.set(CollectionTemporary.column_jsrtype, temp.getStr(CollectionTemporary.column_jsrtype))*/
					.set(CollectionTemporary.column_createDate, new Date())
					.set(CollectionTemporary.column_createId, userIds)
					.set(CollectionTemporary.column_status, 1)
					.set(CollectionTemporary.column_fzr, customerDetail.getStr(CustomerDetail.column_chargePersion))
					.set(CollectionTemporary.column_dataStatus, 2);
					if (!temporary.save()) {
						log.debug("测算信息保存失败！！");
						throw new RuntimeException("测算信息保存失败!");
					}
					if(map.get(10)!=null&&!map.get(10).equals("")){
					
					//订单编号
					// 获取进店日期
					SimpleDateFormat df = new SimpleDateFormat("yyMM");
					SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");
					Date date2;
					try {
						date2 = df2.parse(map.get(8));
						String date = df.format(date2);
						// 获取机构编号（门店编号）
						String newNum = "";
						String dlmdBH = BentryRegisterService.getOrgBh(organIds);
						String p = "%" + date + dlmdBH + "%";
						String sqlSelBh = getSqlMy(ProductSalesOrder.sqlId_sleBh);
						List<ProductSalesOrder> psoList = ProductSalesOrder.dao.find(sqlSelBh, p);
						if (psoList != null && psoList.size() > 0) {
							String ornum = psoList.get(0).getStr(ProductSalesOrder.column_orderNumber);
							int n = Integer.parseInt(ornum.substring(ornum.length() - 4, ornum.length()));
							newNum = date + dlmdBH + String.format("%04d", n + 1);
							
						} else {
							 newNum = date + dlmdBH + "0001";
						
						}

						String sqllc = "SELECT ids FROM sb_product sp WHERE sp.name = ?";
						if(Db.findFirst(sqllc,map.get(10))!=null){
							String lcIds= Db.findFirst(sqllc,map.get(10)).getStr("ids");
							String numberStr = map.get(11);
							String costStr = map.get(12);
							int number = Integer.parseInt(numberStr);
							float cost = Float.parseFloat(costStr);
							float unitPrice = cost/number;
							// 保存销售订单
							ProductSalesOrder pso = new ProductSalesOrder();
							String psoids = ToolRandoms.getUuid(true);
							String receivableStr =  map.get(12);
							float receivable = Float.parseFloat(receivableStr);
							pso.set(ProductSalesOrder.column_ids, psoids).set(ProductSalesOrder.column_orderNumber, newNum)
									.set(ProductSalesOrder.column_customerIds, customer.getStr(Customer.column_ids))
									.set(ProductSalesOrder.column_organIds, organIds).set(ProductSalesOrder.column_userIds, userIds)
									.set(ProductSalesOrder.column_receivable,receivable)
									.set(ProductSalesOrder.column_proceeds,receivable)
									
									.set(ProductSalesOrder.column_arrears,0)
									.set(ProductSalesOrder.column_date,date2).set(ProductSalesOrder.column_gxsj,date2);
							
							if (!pso.save()) {
								log.debug("保存产品订单失败！！");
								throw new RuntimeException("保存产品订单失败!");
							}else{
								// 保存店面销售记录
								String psids = ToolRandoms.getUuid(true);
								ProductSales ps = new ProductSales();
								ps.set(ProductSales.column_ids, psids)
										.set(ProductSales.column_orderIds, pso.getStr(ProductSalesOrder.column_ids))
										.set(ProductSales.column_organids, organIds)
										.set(ProductSales.column_customerID, customer.getStr(CustomerProduct.column_ids))
										.set(ProductSales.column_type, "455018290a8f4afbbaf29c61904d6406")
										.set(ProductSales.column_productID, lcIds)
										.set(ProductSales.column_number, number)
										.set(ProductSales.column_userID, userIds)
										.set(ProductSales.column_unitPrice,unitPrice)
										.set(ProductSales.column_price, cost)
										.set(ProductSales.column_date,date2)
										.set(ProductSales.column_consumerType, Code.xflb_gm);
								if (!ps.save()) {
									log.debug("保存产品销售记录失败！！");
									throw new RuntimeException("保存产品销售记录失败!");
								}
							}
							
							//保存日销售综合表
							DailyNursingTotal  dnt = DailyNursingTotal.dao.getDnt(organIds,customerDetail.getDate(CustomerDetail.column_firstDate));
							
							if(dnt != null)
							{
											if(customerDetail.getStr(CustomerDetail.column_type)!=null){
												String jdfsStr =customerDetail.getStr(CustomerDetail.column_type);
												dnt.set(DailyNursingTotal.column_cjrs, dnt.getInt(DailyNursingTotal.column_cjrs)+1);
												
													if(jdfsStr.equals(Code.zjs_ids))//如果是转介绍
													{
														dnt.set(DailyNursingTotal.column_zjscjrs, dnt.getInt(DailyNursingTotal.column_zjscjrs)+1);
													}else if(jdfsStr.equals(Code.xc_ids))
													{
														dnt.set(DailyNursingTotal.column_xccjrs, dnt.getInt(DailyNursingTotal.column_xccjrs)+1);
													}else
													{
														dnt.set(DailyNursingTotal.column_zrjdcjrs, dnt.getInt(DailyNursingTotal.column_zrjdcjrs)+1);
													}
												}
											
											
											
											
											//保存疗程
											if(map.get(10)!=null&&!map.get(10).equals("")){
												if(lcIds!=null && lcIds.equals("4777c2c215b6408ab13c1eac4190ce46")){
													dnt.set(DailyNursingTotal.column_LC002SalNum, dnt.getInt(DailyNursingTotal.column_LC002SalNum)+1)
														.set(DailyNursingTotal.column_LC002SalPrice, dnt.getDouble(DailyNursingTotal.column_LC002SalPrice)+(double)receivable)
														.set(DailyNursingTotal.column_priceTotal,dnt.getDouble(DailyNursingTotal.column_priceTotal)+(double)receivable);
													
												}else if (lcIds!=null && lcIds.equals("0896ce4d4970455d9184e6dd1ced6a0e")){
													dnt.set(DailyNursingTotal.column_LC001SalNum, dnt.getInt(DailyNursingTotal.column_LC001SalNum)+number)
													.set(DailyNursingTotal.column_LC001SalPrice, dnt.getDouble(DailyNursingTotal.column_LC001SalPrice)+(double)receivable)
													.set(DailyNursingTotal.column_priceTotal,dnt.getDouble(DailyNursingTotal.column_priceTotal)+(double)receivable);
												}
											}
											
											if (!dnt.update()) {
												log.debug("更新日护理综合查询失败！！");
												throw new RuntimeException("更新日护理综合查询失败!");
											}	
										
							}else
							{	
								DailyNursingTotal  dntNew = new DailyNursingTotal();
								if(customerDetail.getStr(CustomerDetail.column_type)!=null){
								String jdfsStr =customerDetail.getStr(CustomerDetail.column_type);
								if(jdfsStr.equals(Code.zjs_ids))//如果是转介绍
								{
									dntNew.set(DailyNursingTotal.column_zjscjrs, 1);
								}else if(jdfsStr.equals(Code.xc_ids))
								{
									dntNew.set(DailyNursingTotal.column_xccjrs, 1);
								}else
								{
									dntNew.set(DailyNursingTotal.column_zrjdcjrs, 1);
								}
								}
								
								dntNew.set(DailyNursingTotal.column_organids, organIds)
									  .set(DailyNursingTotal.column_date, ToolDateTime.format(customerDetail.getDate(CustomerDetail.column_firstDate), ToolDateTime.pattern_ymd))
									  .set(DailyNursingTotal.column_cjrs,1);
								
								//保存疗程
								if(map.get(10)!=null&&!map.get(10).equals("")){
									if(lcIds!=null && lcIds.equals("4777c2c215b6408ab13c1eac4190ce46")){
										dntNew.set(DailyNursingTotal.column_LC002SalNum, 1)
											.set(DailyNursingTotal.column_LC002SalPrice,(double)receivable)
											.set(DailyNursingTotal.column_priceTotal,(double)receivable);
										
									}else if (lcIds!=null && lcIds.equals("0896ce4d4970455d9184e6dd1ced6a0e")){
										dntNew.set(DailyNursingTotal.column_LC001SalNum, number)
										.set(DailyNursingTotal.column_LC001SalPrice,(double)receivable)
										.set(DailyNursingTotal.column_priceTotal,(double)receivable);
									}
								}
								if (!dntNew.save()) {
									log.debug("更新日综合查询表失败");
									throw new RuntimeException("更新日综合查询表失败!");
								}
							}
							
						}
					
						
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					}
					
					}}
					
			
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			json.put("message", "文件未找到");
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			json.put("message", "请重新选择文件");
			e.printStackTrace();
		}
		
		return json;
		}

	/*public void huifu() {
		
		String sql = "select * FROM sb_customer_detail where height = '0'";
		  List<CustomerDetail>  r = CustomerDetail.dao.find(sql);
		  int num = r.size();
		  System.out.println(num);
		  for (CustomerDetail cDetail : r) {
			  String name = cDetail.getStr(CustomerDetail.column_name);	
			  String organIds = cDetail.getStr(CustomerDetail.column_organIds);	
			  String sqlTem = "SELECT * from sb_customer_temporary where name = ? and organIds = ? ";
			  Temporary temporary = Temporary.dao.findFirst(sqlTem,name,organIds);
			  if(temporary!=null){
				  cDetail.set(CustomerDetail.column_height, temporary.getInt(Temporary.column_height));
			  }
			
			  cDetail.update();
		  }
		  
		  
		
		String sqllc = "SELECT   c.*   from sb_customer c  LEFT JOIN sb_customer_detail  d ON  c.ids = d.customerIds  WHERE  d.customerIds is  NULL";
		
		
	  List<Record>  r = 	Db.find(sqllc);
	  
	  for (Record record : r) {
		  
		  String customerIds = record.getStr(Customer.column_ids);	
		  String organIds = record.getStr(Customer.column_organIds);
		  String sqlOrg = "select * from sys_organization where ids = ?";
		  
		  
		  String orhName = Db.findFirst(sqlOrg,organIds).getStr("name");
		  String fzr = Db.findFirst(sqlOrg,organIds).getStr("agentIds");
		  
		  String hybh = record.getStr(Customer.column_hybh);
		  String name = record.getStr(Customer.column_name);
		  String sex = record.getStr(Customer.column_sex);	
		  int age = record.getInt(Customer.column_age);	
		  String phone = record.getStr(Customer.column_phone);	
		  Date registtime = record.getDate(Customer.column_registtime);	
		  String sqlAgree = "select * from sb_customer_agreement where state='1' and customerIds = ?  and  organIds=?";
		  CustomerAgreement customerAgreement = CustomerAgreement.dao.findFirst(sqlAgree,customerIds,organIds);
		  String sqltem = "select * from sb_customer_temporary where phone = ?";
		  float firstWeight = 0;
		  float afterWeight =0;
		  float delWeight = 0;
		  float stWeight =0;
		  Temporary temporary = Temporary.dao.findFirst(sqltem,phone);
		  int height = 0;
		  if(customerAgreement!=null){
			  firstWeight = customerAgreement.getFloat(CustomerAgreement.column_before_weight);
			  afterWeight = customerAgreement.getFloat(CustomerAgreement.column_after_weight);
			  stWeight = customerAgreement.getFloat(CustomerAgreement.column_std_weight);
			   delWeight = firstWeight-afterWeight;
		  }else{
			  if(temporary!=null){
				 firstWeight = temporary.getFloat(Temporary.column_weight);
				   afterWeight = temporary.getFloat(Temporary.column_targetWeight);
				   stWeight = temporary.getFloat(Temporary.column_standWeight);
				 delWeight = firstWeight-afterWeight;
				  height = temporary.getInt(Temporary.column_height);
			  }
		  }
		 
		  
		
		 CustomerDetail customerDetail = new CustomerDetail();
		 customerDetail.set(customerDetail.column_customerIds, customerIds)
		 .set(customerDetail.column_organIds, organIds)
		 .set(customerDetail.column_hybh, hybh)
		 .set(customerDetail.column_name, name)
		 .set(customerDetail.column_phone, phone)
		 .set(customerDetail.column_toStoreDate, registtime)
		 .set(customerDetail.column_firstDate, registtime)
		 .set(customerDetail.column_minDate, registtime)
		 .set(customerDetail.column_organName, orhName)
		 .set(customerDetail.column_firstWeight, firstWeight)
		 .set(customerDetail.column_delWeight, delWeight)
		 .set(customerDetail.column_nowWeight, firstWeight)
		 .set(customerDetail.column_standardWeight, stWeight)
		 .set(customerDetail.column_minWeight, firstWeight)
		 .set(customerDetail.column_dataStatus, 2)
		 .set(customerDetail.column_targetWeight, afterWeight)
		 .set(customerDetail.column_type, "7728a6bfa5c044a9bd69d99b2d7e7d94")
		 .set(customerDetail.column_customerType, "0")
		 .set(customerDetail.column_chargePersion, fzr)
		 .set(customerDetail.column_height, height);
		 
		 customerDetail.save();
		  
		  
		
	}
		
		// TODO Auto-generated method stub
		
	}
	
	
	*/

	

}
